package com.gmlive.plugin.jenkins

import okhttp3.*
import org.json.JSONObject
import java.io.File

/**
 * author: fanfeiyue
 * time: 2020/10/29
 * des:
 */
object FirUtils {

    fun uploadFir(jenkinsConfig: JenkinsExtension, jenkinsOptions: JenkinsOptions) {

        val bundleId = jenkinsOptions.packageName
        val apiToken = jenkinsConfig.firApiToken
        val versionName = jenkinsOptions.versionName
        val versionCode = jenkinsOptions.versionCode
        val appName = jenkinsConfig.firAppName
        val apkFile = File(jenkinsOptions.srcApkFile)

        val client = OkHttpClient()

        val binaryJSONObj = JSONObject(getUploadCert(bundleId, apiToken)).getJSONObject("binary")

        val uploadUrl = binaryJSONObj["upload_url"] as String
        val key = binaryJSONObj["key"] as String
        val token = binaryJSONObj["token"] as String

        val fileReq = RequestBody.create(MediaType.parse("application/octet-stream"), apkFile)

        val multipartBody = MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("key", key)
                .addFormDataPart("token", token)
                .addFormDataPart("x:name", appName)
                .addFormDataPart("x:version", versionName)
                .addFormDataPart("x:build", versionCode.toString())
                .addFormDataPart("x:changelog", "jenkins提交-JOB NAME：${jenkinsOptions.buildName}-JOB ID：${jenkinsOptions.buildId}-操作人：${jenkinsOptions.buildUser}")
                .addFormDataPart("file", apkFile.name, fileReq)
                .build()
        val req = Request.Builder()
                .url(uploadUrl)
                .post(multipartBody)
                .build()

        val response = client.newCall(req).execute()

        println("[Jenkins] upload fir response : ${response.body()?.string()}")
    }

    private fun getUploadCert(bundleId: String, apiToken: String): String {

        println("[Jenkins] bundleId = $bundleId, apiToken = $apiToken")

        val client = OkHttpClient()

        val bodyJsonObj = JSONObject().apply {
            put("type", "android")
            put("bundle_id", bundleId)
            put("api_token", apiToken)
        }

        val bodyReq = FormBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJsonObj.toString())
        val req = Request.Builder()
                .url("http://api.bq04.com/apps")
                .post(bodyReq)
                .build()

        val response = client.newCall(req).execute()

        val result = response.body()?.string()

        println("[Jenkins] get upload cert response : $result")

        return JSONObject(result).opt("cert").toString()
    }

}